import React, { useState, useEffect } from "react"
import { useHistory } from "react-router-dom"
import { Button } from "antd"
import { useDispatch } from "react-redux"
import { setUserInfo } from "reducers/userInfo"

import "./index.scss"
import icon from "assets/img/icon/icon.svg"

import { captcha, login } from "api/login"
import { useKeyPress } from "hooks"

// https://www.bootstrapdash.com/demo/majestic-admin-pro/template/demo/vertical-default-light/pages/samples/login.html
const Login: React.FC = () => {
  const history = useHistory()
  const dispatch = useDispatch()

  const [verifyCode, setVerifyCode] = useState("")
  const [form, setForm] = useState({
    username: "admin",
    password: "123456",
    captcha: "",
    captchaId: ""
  })

  const onChange = (data) => {
    setForm({ ...form, ...data })
  }

  const refresh = async () => {
    const { code, data } = await captcha()
    if (code === 200) {
      onChange({ captchaId: data.captchaId })
      setVerifyCode(data.picPath)
    }
  }

  useEffect(() => {
    refresh()
  }, [])

  const submit = async () => {
    try {
      const { code, data } = await login(form)
      if (code === 200) {
        dispatch(setUserInfo(data))
        history.push("/about1")
      }
    } catch (e) {
      console.log(e)
    }
  }

  // enter按键
  useKeyPress("Enter", submit)

  return (
    <div className="login flex justify-center items-center">
      <div className="form-content bg-white">
        <img className="icon" src={icon} alt="" />
        <h2>Hello! let&apos;s get started</h2>
        <p>Sign in to continue.</p>
        <div className="form-group">
          <input
            value={form.username}
            placeholder="请输入用户名"
            onChange={(e) => onChange({ username: e.target.value })}
          />
        </div>
        <div className="form-group">
          <input
            type="password"
            value={form.password}
            placeholder="请输入密码"
            onChange={(e) => onChange({ password: e.target.value })}
          />
        </div>
        <div className="form-group flex justify-between items-center">
          <input
            value={form.captcha}
            placeholder="请输入验证码"
            onChange={(e) => onChange({ captcha: e.target.value })}
          />
          <img
            className="icon ml20"
            src={verifyCode}
            alt=""
            onClick={refresh}
          />
        </div>
        {/* <Checkbox onChange={onChange} style={{ marginTop: 15 }}>
          自动登录
        </Checkbox> */}
        <Button className="button" type="primary" onClick={submit}>
          登 录
        </Button>
      </div>
    </div>
  )
}

export default Login
